<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"-->
<!--        integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">-->
  <link rel="stylesheet" href="../css/common.css">
<!--  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">-->
<!--  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>-->
  <script src="/js/chart.js"></script>
<!--  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>-->
  <title>消息</title>
</head>
<body>
<div th:replace="common/top"></div>

<div id="w">

  <div class="chat">
    <div class="chat-container">
      <div id="title">Admin</div>
      <div class="chat-display">
        <!-- 对话展示框将在这里 -->
      </div>
      <div class="chat-input">
        <input type="text" id="message-input" placeholder="请输入内容">
        <div>
          <button id="submitBtn" class="Button" onclick="sendMsg()">发  送</button>
        </div>
      </div>

    </div>
  </div>
  <script th:inline="javascript">
    const wsMap = {}; // 用于存储WebSocket对象的Map
    var ws;
    const chatDisplay = document.querySelector('.chat-display');
    const messageInput = document.getElementById('message-input');
    const submitBtn = document.getElementById('submit-btn');
    const messages=[];//改了{}
    var customerID = [[${session.loginUser.username}]]
    console.log("customerID" + customerID)
    var username;
    // const msgList=document.querySelector(".msgrows");
    window.addEventListener('load',function (){
      const Url = 'ws://localhost:8080/chat/' + customerID;
      createWebSocket(Url);
    })

    window.addEventListener('beforeunload', function() {//离开页面时关闭Websocket连接
      console.log('close');
      ws.close();
    });

    function createWebSocket(url) {
      // if(ws!=null){
      //   ws.close();
      // }

      // if (!wsMap[url]) {
      ws = new WebSocket(url);
      console.log("cj")
      wsMap[url] = ws;
      ws.userType="user";
      // 设置WebSocket事件处理
      ws.onopen = function(event) {
        console.log('WebSocket 连接成功');
      };
      ws.onclose=function (event) {
        console.log('close');

        var url = `/user/closeChat`;

        console.log("关闭的是"+ username);
        fetch(url,{
          method:'GET'
        }) .then(response => response.json())
                .catch(error => {
                  console.error('请求发送失败:', error);
                });
      }

      ws.onmessage = function(event) {
        chatDisplay.innerHTML = '';
        // 处理接收到的消息
        const msg = JSON.parse(event.data);
        console.log('onmessage');

        console.log(event.data)
        console.log(msg);

        msg.forEach(function (message) {
          const content = message.content;
          console.log(content)//ok,message为数组
          const time = new Date(message.createTime).toLocaleString();
          const userId = message.username;
          const adminId = message.adminname;
          const direction = message.direction;
          const messageItem = document.createElement('li');
          if(direction === 1){
            messageItem.textContent = `${time}:\n${content}`;
            messageItem.style.color = 'green';
            messageItem.style.textAlign = 'right';
            messageItem.style.padding = '3px';
            messageItem.style.margin = '5px 5px 0 5px';
            messageItem.style.whiteSpace = 'pre-wrap'; // 设置文本换行方式
            messageItem.style.display = 'block'; // 设置每个 li 元素独占一行
          }
          else{
            messageItem.textContent = `${time}\n${content}`;
            messageItem.style.color ='blue';
            messageItem.style.textAlign ='left';
            messageItem.style.padding ='3px';
            messageItem.style.margin ='5px 5px 0 5px';
            messageItem.style.whiteSpace = 'pre-wrap'; // 设置文本换行方式
            messageItem.style.display = 'block'; // 设置每个 li 元素独占一行
          }
          // messageItem.style.color = direction === 1 ? 'blue' : 'green'; // 根据方向设置消息颜色
          // - Admin ${adminId} to User ${userId}:
                  messageItem.style.backgroundColor='white';
          // 将消息添加到消息列表中
          console.log(messageItem);
          chatDisplay.appendChild(messageItem);
        })
      };
    }

    function sendMsg(){
      var time = Date.now();
      var date = new Date(time);
      // var formattedDate = date.toISOString().slice(0, 19).replace('T', ' ');

      var year = date.getFullYear();
      var month = String(date.getMonth() + 1).padStart(2, '0');
      var day = String(date.getDate()).padStart(2, '0');
      var hours = String(date.getHours()).padStart(2, '0');
      var minutes = String(date.getMinutes()).padStart(2, '0');
      var seconds = String(date.getSeconds()).padStart(2, '0');

// 构造日期时间字符串
      var formattedDate = year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
      console.log(formattedDate)
      const message = messageInput.value;
      let sendObject=JSON.stringify({
        content:message,
        createTime:formattedDate,
        username:customerID,
        adminname:null,
        direction:1 });
      console.log(sendObject);
      ws.send(sendObject);
      messageInput.value = ''; // 清空输入框
    }
  </script>
</div>
<div th:replace="common/bottom"></div>

</body>
</html>